<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Prize extends Model
{
	protected $table = 'prize';

	/**
	 * 获取奖池和更新奖池
	 * User: ihome
	 * @return array
	 * @throws \Psr\SimpleCache\InvalidArgumentException
	 */
	public function getPrizeArrFromCache()
	{
		//奖品列表
		$prizeList = Prize::all()->toArray();

		//构成这个奖池的数组
		$prizeArr = [];

		//奖池有奖品才执行
		if ($prizeList) {
			//取出最小的概率
			$probabilityColunm = array_column($prizeList, 'probability');
			//去除没有概率的 为0的
			$probabilityColunm = array_filter($probabilityColunm);
			asort($probabilityColunm, SORT_NUMERIC);
			$min_probability = array_values($probabilityColunm)['0'];

			//根据最小的概率，算出要乘于的基数
			$probabilityLeng = strlen(strstr($min_probability, '.'));
			//等到奖池基数后乘于100 获得完整的奖池基数
			$ticket = (int)str_pad('1', $probabilityLeng, '0');
			$ticket = $ticket * 100;

			//循环奖品
			foreach ($prizeList as $k => $v) {
				//收录到map中
				$prizeMap[$v['id']] = $v['prize_name'];

				//计算产品概率 概率 / 100 * 1000（奖池总数）
				$num          = $v['probability'] / 100;
				$prizePoolNum = $num * $ticket;

				//填充奖池
				$arr = [];
				if ($prizePoolNum >= 1) {
					$arr      = array_pad($arr, $prizePoolNum, $v['prize_name']);
					$prizeArr = array_merge($prizeArr, $arr);
				}
			}

			//剩下的 填入谢谢惠顾
			$popIndex = count($prizeArr);
			$thinks   = [];
			if (($ticket - $popIndex) > 0) {
				$thinks = array_fill($popIndex, $ticket - $popIndex, '谢谢惠顾');
			}

			//合并最终奖池
			$prizeArr = array_merge($prizeArr, $thinks);

			//设置2个缓存 一个是数组的Arr
			//另外一个是映射id=>奖品名称
			\Cache::set('prizeArr', $prizeArr, 20);
			\Cache::set('prizeMap', $prizeMap, 20);
			\Cache::set('prizeTicketCount', $ticket, 20);//奖池总数

		}

		return $prizeArr;
	}

}
